#include <iostream>
#include "HanoiTower.h"

using namespace std;

/*
http://en.wikipedia.org/wiki/Tower_of_Hanoi 
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, 
and a number of disks of different sizes which can slide onto any rod. The puzzle 
starts with the disks in a neat stack in ascending order of size on one rod, the 
smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:
1) Only one disk may be moved at a time.
2) Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, 
   on top of the other disks that may already be present on that rod.
3) No disk may be placed on top of a smaller disk.

*/

Tower::Tower(int Index)
{
	this->Index = Index;
};

void Tower::MoveDisks(int DiskCount, Tower *Destination, Tower *Buffer)
{
	if( !DiskCount )
	{
		return;
	}

	MoveDisks( DiskCount-1, Buffer, Destination );
	MoveTopDisk( Destination );
	Buffer->MoveDisks( DiskCount-1,Destination, this ); 
};

void Tower::MoveTopDisk(Tower* Destination)
{
	if( Disks.size() )
	{
		Destination->Add(Disks.top());
		cout<<"Move Disk "<<Disks.top()<<" from Tower "<<Index<<" to "<<Destination->GetIndex()<<endl;
		Disks.pop();
	}
};

void Tower::PrintTower()
{
	cout<<"Tower "<<Index<<" has "<<Disks.size()<<" Disks"<<endl;
	return;
}

int Tower::GetIndex()
{
	return Index;
}

bool Tower::Add( int Data )
{
	if( !Disks.empty() && Data >= Disks.top() )
	{
		cout<<"Invalid move on tower "<<Index<<endl;
		return false;
	}
	Disks.push(Data);
	return true;
}

int main()
{
	Tower *towers[3];
	int diskNumber = 10;

	for( int i=0; i<3; i++)
	{
		towers[i] = new Tower(i);
	}

	for( int i=10; i>0;i-- )
	{
		if( !towers[0]->Add( i ) )
		{
			cout<<"fail"<<endl;
			goto end;
		}
	}
	
	towers[0]->MoveDisks(diskNumber, towers[2], towers[1]);

	for( int i=0; i<3; i++ )
	{
		towers[i]->PrintTower();
		delete towers[i];
	}
	
end:

	cout<<"Press any key to terminate ..."<<endl;
	return getchar();
}

